package cn.huiyunche.bms.web.controller;

import cn.huiyunche.bms.backend.bo.ReceivableFeeDetailorTempBO;
import cn.huiyunche.bms.backend.query.BmsReceivableBillConditions;
import cn.huiyunche.bms.backend.query.SServiceOrderConditions;
import cn.huiyunche.bms.backend.service.ReceivableService;
import cn.huiyunche.bms.web.vo.ReceivableBillVO;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * Created by felix on 2017/7/7 0007.
 */

@Controller
@RequestMapping("/receivable")
public class ReceivableController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReceivableController.class);

    @Autowired
    private ReceivableService receivableService;

    /**
     * 跳转账单列表页面
     * @return
     * @throws Exception
     */
//    @RequestMapping("/to-index")
//    public String toListPage(HttpServletResponse response) throws Exception{
//        response.setHeader("X-Frame-Options","SAMEORIGIN");
//        return "index";
//    }

    /**
     * 查询账单列表
     * @param pageVo
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/rece-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> listByPage(PageVo pageVo, ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.listByPage params : {}, {}", pageVo, vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            BmsReceivableBillConditions conditions = new BmsReceivableBillConditions();
            BeanUtils.copyProperties(vo,conditions);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (vo.getBillDateStartString() != null)
                conditions.setBillDateStart(format.parse(vo.getBillDateStartString()));
            if (vo.getBillDateEndString() != null)
                conditions.setBillDateEnd(format.parse(vo.getBillDateEndString()));
            result.setData(receivableService.selectReceivableByConditions(pageVo, conditions));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.listByPage error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 跳转新建账单初始列表页面
     * @return
     * @throws Exception
     */
//    @RequestMapping("/to-order-list")
//    public String toOrderListPage(HttpServletResponse response) throws Exception{
//        response.setHeader("X-Frame-Options","SAMEORIGIN");
//        return "index";
//    }

    /**
     * 新建账单初始订单列表
     * @param pageVo
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/order-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> orderList(PageVo pageVo, ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.orderList param : {}", pageVo, vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            SServiceOrderConditions conditions = new SServiceOrderConditions();
            BeanUtils.copyProperties(vo,conditions);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (vo.getBillDateStartString() != null)
                conditions.setCreateTimeStart(format.parse(vo.getBillDateStartString()));
            if (vo.getBillDateEndString() != null)
                conditions.setCreateTimeEnd(format.parse(vo.getBillDateEndString()));
            result.setData(receivableService.selectServiceOrderByConditions(pageVo, conditions));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.orderList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 新建账单下一步插入临时表
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/insert-temp", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> insertTemp(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.insertTemp param : {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "新建成功");
        try {
            result.setData(receivableService.insertTemp(vo.getOrderIds()));;
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.insertTemp error: {}", e);
//            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 跳转新建账单下一步临时表列表页面
     * @return
     * @throws Exception
     */
//    @RequestMapping("/to-temp-list")
//    public String toTempListPage(HttpServletResponse response) throws Exception{
//        response.setHeader("X-Frame-Options","SAMEORIGIN");
//        return "index";
//    }

    /**
     * 新建账单临时表列表
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/temp-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> tempList(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.tempList param : {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            result.setData(receivableService.selectReceivableDetailTemp(vo.getVersionNo()));

        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.tempList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 调整金额
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update-temp", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> updateTemp(ReceivableBillVO vo, BindingResult br) throws Exception {
        LOGGER.info("ReceivableController.updateRece param : {}",  vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认成功");
        try {
            ReceivableFeeDetailorTempBO bo = new ReceivableFeeDetailorTempBO();
            BeanUtils.copyProperties(vo, bo);
            result.setData(receivableService.updateReceivableDetailTemp(bo, br));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.updateRece error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 生成账单
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/create-rece", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> createRece(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.createRece param : {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String username = (String)session.getAttribute("username");
            receivableService.createRece(vo.getVersionNo(), vo.getInvoiceStatus(), username);
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.createRece error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 跳转确认账单列表页面
     * @return
     * @throws Exception
     */
//    @RequestMapping("/to-confirm-list")
//    public String toConfirmListPage(HttpServletResponse response) throws Exception{
//        response.setHeader("X-Frame-Options","SAMEORIGIN");
//        return "index";
//    }

    /**
     * 确认账单列表
     * @param pageVo
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/confirm-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> confirmList(PageVo pageVo, ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.confirmList param : {}", pageVo, vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            result.setData(receivableService.selectReceivableDetailByConditions(pageVo, vo.getId()));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.confirmList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 确认账单
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/confirm-rece", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> confirmRece(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.confirmList param : {}",  vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认成功");
        try {
            result.setData(receivableService.confirmBill(vo.getId(), vo.getInvoiceStatus()));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.confirmList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 调整金额
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update-detl", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> updateRece(ReceivableBillVO vo, BindingResult br) throws Exception {
        LOGGER.info("ReceivableController.updateRece param : {}",  vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认成功");
        try {
            ReceivableFeeDetailorTempBO bo = new ReceivableFeeDetailorTempBO();
            BeanUtils.copyProperties(vo, bo);
            result.setData(receivableService.updateReceivableDetail(bo, br));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.updateRece error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 删除账单
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-rece", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deleteRece(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.deleteRece param : {}",  vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "删除成功");
        try {
            result.setData(receivableService.deleteReceivable(vo.getOrderIds()));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.deleteRece error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 移除明细账单的订单
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-rece-detl", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deleteReceivableDetail(Integer id) throws Exception {
        LOGGER.info("ReceivableController.deleteReceivableDetail param : {}",  id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "删除成功");
        try {
            result.setData(receivableService.deleteReceivableDetail(id));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.deleteReceivableDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 移除明细账单的临时订单
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-detl-temp", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deleteReceivableDetailTemp(Integer id) throws Exception {
        LOGGER.info("ReceivableController.deleteReceivableDetailTemp param : {}",  id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "删除成功");
        try {
            result.setData(receivableService.deleteReceivableDetailTemp(id));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.deleteReceivableDetailTemp error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 查询客户
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/select-cust", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> selectConsignorName() throws Exception {
        LOGGER.info("ReceivableController.selectConsignorName param : {}");
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            result.setData(receivableService.selectConsignorName());
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.selectConsignorName error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 确认收款
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/confirm-proceed", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> confirmProceed(ReceivableBillVO vo) throws Exception {
        LOGGER.info("ReceivableController.confirmProceed param : {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认收款");
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
//            String usercode = (String)session.getAttribute("usercode");
            String usercomment = (String)session.getAttribute("usercomment");
            result.setData(receivableService.confirmProceed(vo.getId(), vo.getBillDateStartString(), vo.getBillDateEndString(), usercomment));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("ReceivableController.confirmProceed error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 导出excel
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(ReceivableBillVO vo, HttpServletRequest request,  HttpServletResponse response) throws Exception {
        LOGGER.info("ReceivableController.export param : {}", vo);
        try {
            receivableService.exportExcel(vo.getOrderIds(), request, response);
        } catch (Exception e) {
            LOGGER.error("ReceivableController.export error: {}", e);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 收款确认导出excel
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export-proceed")
    @ResponseBody
    public void exportProeed(ReceivableBillVO vo, HttpServletRequest request,  HttpServletResponse response) throws Exception {
        LOGGER.info("ReceivableController.exportProceed param : {}", vo);
        try {
            receivableService.exportProceed(vo.getOrderIds(), request, response);
        } catch (Exception e) {
            LOGGER.error("ReceivableController.exportProceed error: {}", e);
            throw new BusinessException(e.getMessage());
        }
    }
}
